//
//  DetailHouseTypeSubVc.m
//  WGFGlobalHouses
//
//  Created by waiguofang on 15/5/20.
//  Copyright (c) 2015年 waiguofang. All rights reserved.
//

#import "DetailHouseTypeSubVc.h"
#import "HouseListDataManage.h"
#import "NodataCell.h"
#import "MBProgressHUD+MJ.h"
#import "MJRefresh.h"
#import "HouseTypeView.h"
#import "HouseTypeViewCell.h"
#import "config.h"
#import "HouseTypeViewController.h"

#import "UserModal.h"
#import "DetailMainTableViewController.h"
#import "HouseTypeCellModel.h"
#import "NSString+category.h"

@interface DetailHouseTypeSubVc ()<UITableViewDelegate,UITableViewDataSource,HouseTypeViewDelegate>

@property (strong, nonatomic) UITableView *tableView;

//保存选中的按钮
@property (strong, nonatomic) UIButton *seletedBtn;

//保存列表的数据
@property (nonatomic,strong)NSArray *dataArray;

@property (nonatomic,strong)NodataCell *nodataCell;

@property (strong, nonatomic) HouseListDataManage *dataManage;

@property (nonatomic,copy)NSString *isForwardDelivery; //#pragma mark 请求数据 isForwardDelivery = 3 全部，0现房，1期房



@end

@implementation DetailHouseTypeSubVc
@synthesize dataArray,nodataCell;

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self initView];
   
}


-(void)initView
{
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,self.view.frame.size.width, self.view.frame.size.height-114) ];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    [self.tableView setBackgroundColor:[UIColor whiteColor]];
    self.tableView.allowsSelection = NO;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
   

    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
     [self refreshDataWithIsForwardDelivery:self.ForwardDelivery];
    
    
    [self addPulRefresh];
    [self addLegendHeaderRefresh];
    
}

-(HouseListDataManage *)dataManage
{
    if (!_dataManage)
    {
        _dataManage = [[HouseListDataManage alloc]init];
    }
    return _dataManage;
}

-(void)loadMoreData
{
    NSString *preisesId = self.premisesId;
    NSString *isForwardDelivery = self.isForwardDelivery;
    NSString *consumerId = [NSString stringWithFormat:@"%zd",[UserModal shareUserModel].userId];
    
    
    __block typeof(self) bself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSArray *arr  =[self.dataManage loadMoreDataWithPremisesId:preisesId WithIsForwardDelivery:isForwardDelivery WithConsumerId:consumerId];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView.footer endRefreshing];
            
            NSMutableArray *array = [NSMutableArray arrayWithArray:self.dataArray];
            [array addObjectsFromArray:arr];
            self.dataArray = [NSArray arrayWithArray:array];
            [self dealArr];
            
            if (arr.count == 0 || arr == nil)
            {
                [self.tableView.footer noticeNoMoreData];
            }
                        
            if (dataArray==nil) {//网络出错
                [bself.nodataCell setState:nodataCellStateNetError];
                
            }else if(dataArray.count==0){//没数据
                [bself.nodataCell setState:nodataCellStateNodata];
            }else{//有数据
                
                [bself.nodataCell setState:nodataCellStateNorMal];
            }
            
            [bself.tableView reloadData];
            
        });
    });
    
}

#pragma mark 把已售的排到后边
-(void)dealArr
{
    NSMutableArray *soldArr = [[NSMutableArray alloc]init];//已售的
    NSMutableArray *unSoldArr = [[NSMutableArray alloc]init];//非已售的
   
    
    for (HouseTypeCellModel *model in self.dataArray) {
       
        if ([model.houseTypeName isEqualToString:@"已售"]) {
            [soldArr addObject:model];
        }else
        {
            [unSoldArr addObject:model];
        }
    }
    
    [unSoldArr addObjectsFromArray:soldArr];
    self.dataArray = [NSArray arrayWithArray:unSoldArr];
    
}

#pragma mark 下拉加载
-(void)addLegendHeaderRefresh
{
    __block typeof(self) bself = self;
   
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        [bself loadMoreData];
        
    }];
}


-(void)addPulRefresh
{

   __block typeof(self) bself = self;
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        [bself refreshDataWithIsForwardDelivery:bself.ForwardDelivery];
    }];
}


#pragma mark 请求数据 isForwardDelivery = 3 全部，0现房，1期房
-(void)refreshDataWithIsForwardDelivery:(NSString *)isForwardDelivery
{
    self.isForwardDelivery = isForwardDelivery;
    [self.tableView reloadData];
   
    
     NSString *preisesId = self.premisesId;
    NSString *consumerId = [NSString stringWithFormat:@"%zd",[UserModal shareUserModel].userId];
    [self.nodataCell setState:nodataCellStateLoading];
    [self.tableView.footer resetNoMoreData];
    __block typeof(self) bself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        ResulteMod *mod =[self.dataManage refreshDataWithPremisesId:preisesId WithIsForwardDelivery:isForwardDelivery WithConsumerId:consumerId];
        
        self.dataArray =[[NSArray alloc]initWithArray:mod.dataMod];
        self.otherArr = [NSArray arrayWithArray:mod.otherDataMod];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self dealArr];
            [self.tableView.header endRefreshing];
            
            self.lab1.text = [self.otherArr objectAtIndex:2];
            self.lab2.text =[self.otherArr objectAtIndex:1];
            
            NSString *numStr ;
            if ([[self.otherArr objectAtIndex:0] isKindOfClass:[NSNull class]] || [self.otherArr objectAtIndex:0] == nil)
            {
                numStr = @"0";
    
            }
            else
            {
                numStr = [NSString stringWithFormat:@"%@",[self.otherArr objectAtIndex:0]];
            }

            
            
            if (mod.resltState == ResultNetError) {//网络出错
                
                [bself.nodataCell setState:nodataCellStateNetError];
                
            }else if(mod.resltState == ResultFail){//服务器返回的code出错
                
                [bself.nodataCell setCodeErrorTip:mod.resultCode];
                
            }else{//返回正常
                
                if(bself.dataArray.count==0){//没数据
                    
                    [bself.nodataCell setState:nodataCellStateNodata];
                    
                }else{//有数据
                    
                    [bself.nodataCell setState:nodataCellStateNorMal];
                }
                
                if ([isForwardDelivery isEqualToString:@"3"])
                {
                    [bself.countLab setText:[NSString stringWithFormat:@"全部(%@)",numStr]];
//                    [bself.countLab setAttributedText:[NSString makeLineStyle:[NSString stringWithFormat:@"全部(%@)",numStr] color:[UIColor redColor] fontSize:14]];

                }else if ([isForwardDelivery isEqualToString:@"0"]){
                    
                    [bself.countLab setText:[NSString stringWithFormat:@"现房(%@)",numStr]];
//                    [bself.countLab setAttributedText:[NSString makeLineStyle:[NSString stringWithFormat:@"现房(%@)",numStr] color:[UIColor redColor] fontSize:14]];
                    
                }else{

                    
                    [bself.countLab setText:[NSString stringWithFormat:@"期房(%@)",numStr]];
//                    [bself.countLab setAttributedText:[NSString makeLineStyle:[NSString stringWithFormat:@"期房(%@)",numStr] color:[UIColor redColor] fontSize:14]];

                }
                
            }
            
            [bself.tableView reloadData];
        });
    });
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (dataArray&&dataArray.count>0) {
        [self.tableView setScrollEnabled:YES];
        if (self.dataArray.count%2 == 0)
        {
            return self.dataArray.count/2;
        }
        else
        {
            return self.dataArray.count/2 + 1;
        }
        
    }else{
        [self.tableView setContentOffset:CGPointMake(0, 0)];
        [self.tableView setScrollEnabled:NO];
        return 1;
    }

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (dataArray.count==0) {
        if(!nodataCell){
            nodataCell = [[NodataCell alloc] initWithFrame:self.tableView.frame];
            
            [nodataCell setState:nodataCellStateLoading];
            [[nodataCell refreshBtn]setTag:56];
            [nodataCell.refreshBtn addTarget:self action:@selector(btnOnClick:) forControlEvents:UIControlEventTouchUpInside];
        }
        return nodataCell;
    }
    
    
    HouseTypeCellModel *model1;
    if (indexPath.row*2 < dataArray.count)
    {
        model1 = [dataArray objectAtIndex:indexPath.row*2];
    }
    else
    {
        model1 = nil;
    }
    
    HouseTypeCellModel *model2;
    if (indexPath.row*2 + 1 < dataArray.count)
    {
        model2 = [dataArray objectAtIndex:indexPath.row*2 +1];
    }else
    {
        model2 = nil;
    }
    HouseTypeViewCell *cell = [HouseTypeViewCell cellWithTableView:tableView WithModel1:model1 WithModel2:model2];

    [cell setModel1:model1 WithModel2:model2];
    
    cell.view1.delegate = self;
    cell.view2.delegate = self;
   
    return cell;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

     if (dataArray&&dataArray.count>0)
     {
         return 264;
     }
     else
    {
        return self.tableView.frame.size.height;
    }
    
}
-(void)btnOnClick:(UIButton *)sender{
    
    
    if(sender.tag==56){
        [self refreshData];
    }
}

-(void)houseTypeViewDidClickBtn:(NSInteger)houseId
{
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(DetailHouseTypeSubVcClickBtn:)]) {
        [self.delegate DetailHouseTypeSubVcClickBtn:houseId];
    }
}
@end
